<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="never">
          <el-form ref="queryFormRef" :model="listTreeDTO" :inline="true"
                   style="display: flex;justify-content: space-between">
            <el-form-item label="年-月" prop="contrastDate">
              <el-date-picker
                value-format="YYYY-MM"
                v-model="listTreeDTO.contrastDate"
                type="month"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
              <el-button icon="BottomRight" plain color="green" @click="inherit"
                         v-hasPermi="['budget:management:inherit']">继承
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>
    <el-row :gutter="20">
      <!--   管理部门树列表 -->
      <el-col :lg="7" :xs="24">
        <el-card shadow="never">
          <el-input v-model="name" placeholder="请输入预算部门/预算科目名称" prefix-icon="Search" clearable
                    style="margin-bottom: 10px" />
          <el-tree
            ref="listTreeRef"
            class="filter-tree"
            node-key="id"
            :data="treeList"
            :props="defaultProps"
            :expand-on-click-node="true"
            :filter-node-method="filterNode"
            :highlight-current="true"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="17" :xs="24">
        <el-card shadow="never">
          <template #header>
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['budget:management:add']">新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
                           v-hasPermi="['budget:management:remove']">删除
                </el-button>
              </el-col>
              <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>
          </template>

          <el-table border v-loading="loading" :data="managementList" @selection-change="handleSelectionChange"
                    class="enhanced-table">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="主键id" align="center" prop="id" v-if="false" />
            <el-table-column label="年/月" align="center" prop="contrastDate" width="180" />
            <el-table-column label="预算科目编码" align="center" prop="subjectCode" />
            <el-table-column label="预算部门名称" align="center" prop="subjectName" />
            <el-table-column label="预算申请" align="center" prop="isBudget" width="160">
              <template #default="scope">
                <el-switch
                  v-model="scope.row.isBudget"
                  class="ml-2"
                  style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                  disabled
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="160">
              <template #default="scope">
                <el-tooltip content="删除" placement="top">
                  <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                             v-hasPermi="['budget:management:remove']"></el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

      </el-col>
    </el-row>

    <!-- 继承弹窗 -->
    <el-dialog :title="extendDialog.title" v-model="extendDialog.visible" stripe style="width: 20%" append-to-body>
      <el-form ref="inheritFormRef" :model="inheritData">
        <el-form-item label="继承年月" prop="inheritDate">
          <el-date-picker
            v-model="inheritData.inheritDate"
            type="month"
            value-format="YYYY-MM"
          />
        </el-form-item>
        <el-form-item label="目标年月" prop="targetDate">
          <el-date-picker
            v-model="inheritData.targetDate"
            type="month"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="text-center">
          <el-button type="primary" :loading="buttonLoading" @click="saveInherit">确定</el-button>
          <el-button @click="cancelInherit">取消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 添加对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" style="width:500px" append-to-body>
      <el-form ref="managementFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="预算部门" prop="deptCode">
          <el-select v-model="form.deptCode" placeholder="请选择全部" clearable filterable @change="selectDept" >
            <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptCode+' - '+item.deptName"
                       :value="item.deptCode" />
          </el-select>
        </el-form-item>
        <el-form-item label="预算科目" prop="subjectCode">
          <el-select v-model="form.subjectCode" placeholder="请选择预算科目" clearable filterable
                     @change="selectSubject" >
            <el-option v-for="item in subjectList" :key="item.id" :label="item.subjectCode+' - '+item.subjectName"
                       :value="item.subjectCode" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Management" lang="ts">
import {
  addManagement,
  delManagement,
  getSubjectList,
  listManagement,
  listManagementDept,
  listTree, saveInheritData
} from "@/api/budget/management";
import { ManagementForm, ManagementVO, TreeListDTO, TreeListVO } from "@/api/budget/management/types";
import { ElTree } from "element-plus";
import useDate from "@/hooks/useDate";
import { InheritData } from "@/api/budget/contrastDept/types";
import { DeptVO } from "@/api/system/dept/types";
import { BudgetSubjectVO } from "@/api/budget/budgetSubject/types";
import { verify } from "@/api/budget/contrastDept";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const managementList = ref<ManagementVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);

const queryFormRef = ref<ElFormInstance>();
const managementFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});
// =====================================================================================================================
const listTreeRef = ref<ElTreeInstance>();

const listTreeDTO = ref<TreeListDTO>({
  contrastDate: useDate.getNow(),
  deptCode: undefined
});
const name = ref("");
const defaultProps = {
  id: "id",
  children: "children",
  label: "label"
};
const treeList = ref<TreeListVO[]>([]);

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.name.includes(value);
};

const selectOne = ref<TreeListVO>();
/** 左侧下拉树结构 */
const getTreeSelect = async () => {
  await listTree(listTreeDTO.value).then(res => {
    treeList.value = res.data;
  });
  if (treeList.value.length === 0) {
    return;
  } else {
    loading.value = true;
    await nextTick();
    let firstElement: TreeListVO = treeList.value[0];
    // 默认选中第一个
    listTreeRef.value.setCurrentKey(firstElement.id);
    selectOne.value = firstElement;
    listTreeDTO.value.deptCode = firstElement.code;
    if (firstElement.children != null) {
      //右侧列表
      await getList();
    }
  }

};

/** 节点单击事件 */
const handleNodeClick = (data: TreeListVO) => {
  if (data.children === null) {
    return;
  }
  // 选中的数据
  selectOne.value = data;
  console.log(data);
  //左侧列表参数
  listTreeDTO.value.deptCode = data.code;
  getList();
};
/** 根据名称筛选 */
watchEffect(
  () => {
    listTreeRef.value?.filter(name.value);
  },
  {
    flush: "post" // watchEffect会在DOM挂载或者更新之前就会触发，此属性控制在DOM元素更新后运行
  }
);

/** 查询管理部门科目设置列表 */
const getList = async () => {
  loading.value = true;
  const res = await listManagement(listTreeDTO.value);
  managementList.value = res.data;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  managementFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getTreeSelect();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ManagementVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

// =====================================================添加=============================================================
// 科室下拉框数据
const deptList = ref<DeptVO[]>([]);

const getDeptList = async () => {
  const res = await listManagementDept();
  deptList.value = res.data;
};
//管理科目列表
const subjectList = ref<BudgetSubjectVO[]>([]);
const listSubject = async () => {
  const res = await getSubjectList(listTreeDTO.value.contrastDate);
  subjectList.value = res.data;
};

const initFormData: ManagementForm = {
  deptCode: undefined,
  contrastDate: listTreeDTO.value.contrastDate,
  subjectCode: undefined,
  subjectName: undefined,
  deptName: undefined,
  isBudget: false
};

const rules = ref({
  subjectCode: [
    { required: true, message: "预算科目不能为空", trigger: "change" }
  ],
  deptCode: [
    { required: true, message: "部门不能为空", trigger: "change" }
  ]
});

const form = ref<ManagementForm>({ ...initFormData });
/** 新增按钮操作 */
const handleAdd = async () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加";
  form.value.contrastDate = listTreeDTO.value.contrastDate;
  await getDeptList();
  await listSubject();
};

const selectDept = (value: any) => {
  form.value.deptName = deptList.value.find(item => item.deptCode === value).deptName;
};
const selectSubject = (value: any) => {
  // 根据给定的科目代码(value)从科目列表中查找对应的科目名称和是否预算，并更新表单数据
  form.value.subjectName = subjectList.value.find(item => item.subjectCode === value).subjectName;
  form.value.isBudget = subjectList.value.find(item => item.subjectCode === value).isBudget;
};
/** 提交按钮 */
const submitForm = () => {
  initFormData.contrastDate = listTreeDTO.value.contrastDate;
  managementFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      await addManagement(form.value).finally(() => buttonLoading.value = false).then(() => {
        proxy?.$modal.msgSuccess("操作成功");
      });
      dialog.visible = false;
      await getTreeSelect();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ManagementVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm("是否确认删除选定的数据项？").finally(() => loading.value = false);
  await delManagement(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getTreeSelect();
};

//==========================================================继承===========================================================
// 继承弹窗按钮开关
const extendDialog = reactive<DialogOption>({
  visible: false,
  title: "继承"
});

// 继承数据
const inheritData = reactive<InheritData>({
  inheritDate: undefined,
  targetDate: undefined,
  type: 3
});

// 重置继承数据
const resetInheritData = () => {
  inheritData.inheritDate = undefined;
  inheritData.targetDate = undefined;
};

// 继承按钮
const inherit = () => {
  extendDialog.visible = true;
  inheritData.inheritDate = useDate.getPreviousMonth();
  inheritData.targetDate = useDate.getNow();
};

// 确认继承
const saveInherit = async () => {
  buttonLoading.value = true;
  let msg: string;
  await verify(inheritData).then(res => {
    if (res.data === 1) {
      msg = "继承年月无数据!";
    }
    if (res.data === 2) {
      msg = "目标年月已存在对照数据,是否覆盖?";
    }
    if (res.data === 3) {
      msg = "目标年月无对照数据,是否继承?";
    }
  }).then(() => {
    proxy?.$modal.confirm(msg).then(() => {
      saveInheritData(inheritData);
      proxy?.$modal.msgSuccess("操作成功");
      extendDialog.visible = false;
    }).then(() => {
      getTreeSelect();
    }).catch(() => {
      resetInheritData();
      extendDialog.visible = false;
    });
  }).finally(() => buttonLoading.value = false);
};

// 取消继承
const cancelInherit = () => {
  resetInheritData();
  extendDialog.visible = false;
};
onMounted(() => {
  getTreeSelect();
});
</script>
<style lang="scss" scoped>

:deep(.el-tree) {
  /* 整体样式 */
  background: 	#F0F8FF; /* 背景色 */
  color: #333; /* 文字颜色 */
  font-size: 14px;
  border-radius: 5px;
  padding: 10px;
}

/* 节点高度调整 */
:deep(.el-tree-node) {
  margin: 3px 0;
}

/* 节点悬停效果 */
:deep(.el-tree-node__content:hover) {
  background-color: #E6E6FA !important;
  border-radius: 5px;
}

/* 选中/高亮状态 */
:deep(.el-tree-node:focus > .el-tree-node__content,
.el-tree-node.is-current > .el-tree-node__content) {
  background-color: #87CEFA !important;
  color: #FF1493;
  font-weight: bolder;
  border-radius: 5px;
}

/* 展开/折叠图标优化 */
:deep(.el-tree-node__expand-icon) {
  color: #6495ED;
  font-size: 16px;
  transition: transform 0.3s;
}

/* 展开图标旋转 */
//:deep(.el-tree-node__expand-icon.expanded) {
//  transform: rotate(90deg);
//}


/* 层级线样式（需开启 show-line 属性） */
:deep(.el-tree--line .el-tree-node::before) {
  border-left: 1px dashed #adb5bd;
}

:deep(.el-tree--line .el-tree-node::after) {
  border-top: 1px dashed #adb5bd;
}

/* 节点标签样式 */
:deep(.el-tree-node__label) {
  font-size: 14px;
  padding-left: 6px;
}

/* 复选框样式 */
:deep(.el-checkbox__inner) {
  border-radius: 3px;
}

/* 节点间距调整 */
:deep(.el-tree-node__content) {
  height: 28px; /* 节点高度 */
  line-height: 28px;
}
</style>
